<template>
  <div class="infoWrapper">
    <div class="info">
      <el-button class="verify_btn" @click="handleVerify" type="primary">
        校验
      </el-button>
      <div
        v-show="isDone"
        style="
          position: absolute;
          right: 15%;
          font-weight: bold;
          font-size: 17px;
          color: #555;
        "
      >
        <span>共 {{ moduleSum }} 个模块，</span>
        <span
          @click="skipToNextNoInput"
          style="cursor: pointer; user-select: none"
        >
          未录入 {{ nomatchNum }} 个，
        </span>

        <span
          @click="skipToNextConfigError"
          style="cursor: pointer; user-select: none"
        >
          配置信息错误 {{ configWrongNum }} 个，
        </span>

        <span
          @click="skipToNextAddressError"
          style="cursor: pointer; user-select: none"
        >
          打开地址错误 {{ addresWrongNum }} 个
        </span>
      </div>
    </div>

    <div class="content">
      <slot :tableData="tableData" :version="version" :skipIdx="skipIdx"></slot>
    </div>
  </div>
</template>

<script setup>
import { api_verifyDesktopModule } from "@/api/manage";
import { getCurSchoolInfo } from "@/utils/CommonRequest.js";
import { ElLoading, ElMessage } from "element-plus";
import { ref } from "vue";

const props = defineProps({
  openDraw: Function,
  lastDownloadTime: String,
});

const isDone = ref(false);

const tableData = ref([]);

const curNoMatchIdx = ref(-1);
const curAddressErrorIdx = ref(-1);
const curConfigErrorIdx = ref(-1);
const skipIdx = ref(-1);

const moduleSum = ref(0); //【所有】的模块数量
const nomatchNum = ref(0); //【未匹配】到的模块数量
const addresWrongNum = ref(0); //【打开地址错误】的模块数量
const configWrongNum = ref(0); //【配置信息错误（moduleId、sysId、checkId）】的模块数量

const version = ref(0); //学年阶段

const refresh = async () => {
  console.log("module refresh");
  // 调用getCurSchoolInfo方法，获取version信息
  let schoolInfo = await getCurSchoolInfo();

  version.value = schoolInfo?.SchoolLevel;
};

defineExpose({ refresh });

/**
 * 跳转到下一个未录入的地方
 */
const skipToNextNoInput = () => {
  let i = curNoMatchIdx.value + 1;
  let len = tableData.value.length;
  for (; i < len; i++) {
    const module = tableData.value[i];
    const { instructInfo, moduleInfo } = module;

    if (!moduleInfo?.isMatch) {
      curNoMatchIdx.value = i;
      skipIdx.value = i;
      return;
    }
  }

  curNoMatchIdx.value = -1;
};

/**
 * 跳转到下一个打开地址错误的地方
 */
const skipToNextAddressError = () => {
  let i = curAddressErrorIdx.value + 1;
  let len = tableData.value.length;
  for (; i < len; i++) {
    const module = tableData.value[i];
    const { instructInfo, moduleInfo } = module;

    if (!moduleInfo?.isAddressValid) {
      curAddressErrorIdx.value = i;
      skipIdx.value = i;
      return;
    }
  }

  curAddressErrorIdx.value = -1;
};

/**
 * 跳转到下一个配置信息错误的地方
 */
const skipToNextConfigError = () => {
  let i = curConfigErrorIdx.value + 1;
  let len = tableData.value.length;
  for (; i < len; i++) {
    const module = tableData.value[i];
    const { instructInfo, moduleInfo } = module;

    if (!moduleInfo?.isConfigValid) {
      curConfigErrorIdx.value = i;
      skipIdx.value = i;
      return;
    }
  }

  curAddressErrorIdx.value = -1;
};

const handleVerify = async () => {
  isDone.value = false;
  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "transparent",
  });

  try {
    const { data, success, msg } = await api_verifyDesktopModule();
    if (!success) {
      throw new Error("获取指令失败,接口返回:" + msg);
    }

    let tempTableData = [];

    for (const i in data) {
      const module = data[i];
      const { instructInfo, moduleInfo } = module;
      const { moduleId, appId, linkAppId, accessParam, h5Param } = moduleInfo;

      let isMatch = instructInfo?.length > 0,
        isConfigValid = true,
        isAddressValid = true;

      for (const j in instructInfo) {
        let instruct = instructInfo[j];
        let attribute = JSON.parse(instruct.attribute);

        instruct.attribute = attribute;
        let webUrl = getInstructAccessParam(attribute);
        let h5Url = getInstructH5Param(attribute);
        instruct.webUrl = webUrl;
        instruct.h5Url = h5Url;

        if (
          attribute?.moduleId === moduleId &&
          attribute?.checkId === appId &&
          attribute?.sysId === (linkAppId || appId)
        ) {
          moduleInfo.isConfigValid = true;
          isConfigValid = true;
        } else {
          isConfigValid = false;
        }

        let b1 = true,
          b2 = true;
        if (webUrl?.trim() && accessParam) {
          b1 = instruct?.webUrl === accessParam;
        } else if (webUrl?.trim() || accessParam) {
          b1 = false;
        }
        if (h5Url?.trim() && h5Param) {
          b2 = instruct?.h5Url === h5Param;
        } else if (h5Url?.trim() || h5Param) {
          b2 = false;
        }
        if (b1 && b2) {
          moduleInfo.isAddressValid = true;
          isAddressValid = true;
        } else {
          isAddressValid = false;
        }
      }

      moduleInfo.isMatch = isMatch;
      moduleInfo.isAddressValid = moduleInfo.isAddressValid || isAddressValid;
      moduleInfo.isConfigValid = moduleInfo.isConfigValid || isConfigValid;

      if (!moduleInfo.isConfigValid) {
        configWrongNum.value++;
      }
      if (!moduleInfo.isAddressValid) {
        addresWrongNum.value++;
      }

      tempTableData.push(module);
    }

    tableData.value = tempTableData;
    moduleSum.value = tempTableData.length;

    let nomatchSum = 0;
    tempTableData.forEach((module) => {
      if (module?.instructInfo?.length === 0) {
        nomatchSum++;
      }
    });
    nomatchNum.value = nomatchSum;

    isDone.value = true;
  } catch (e) {
    console.log("e = ", e);
    ElMessage.error("获取数据失败");
  }

  loading.close();
};

const getInstructAccessParam = (attribute) => {
  let v = version.value;
  let item = attribute;

  let urlArr = [];

  if (v === 2) {
    urlArr = item?.middleSchoolUrl?.split(",");
    return urlArr?.[0];
  } else if (v === 1) {
    urlArr = item?.universityUrl?.split(",");
    return urlArr?.[0];
  } else if (v === 4) {
    urlArr = item?.vocationalUrl?.split(",");
    return urlArr?.[0];
  }
};

const getInstructH5Param = (attribute) => {
  let v = version.value;
  let item = attribute;

  let urlArr = [];

  if (v === 2) {
    urlArr = item?.middleSchoolUrl?.split(",");
    return urlArr?.[1];
  } else if (v === 1) {
    urlArr = item?.universityUrl?.split(",");
    return urlArr?.[1];
  } else if (v === 4) {
    urlArr = item?.vocationalUrl?.split(",");
    return urlArr?.[1];
  }
};
const emits = defineEmits(["visibleChange"]);
</script>

<style lang="scss" scoped>
.infoWrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  .info {
    margin: 15px 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    :deep(.el-select) {
      width: 130px;
    }

    .verify_btn {
      width: 120px;
      height: 55px;

      font-size: 18px;
    }
  }
  .content {
    flex: 1;
    min-height: 0;

    box-shadow: 0 1px 6px #0000001a;
    padding-top: 15px;
  }
}
</style>
